package com.soft.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.soft.admin.service.impl.cache.HomeServiceCache;

public class XyAuthenticationSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements AuthenticationSuccessHandler {
	private HomeServiceCache homeServiceCache;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		UserDetails userDetail = (UserDetails)authentication.getPrincipal();
		//清除缓存
		this.homeServiceCache.removeUserCache(userDetail.getUsername());
		this.homeServiceCache.deleteMenuCache(userDetail.getUsername());
		response.sendRedirect("../admin/index.jsp");
        clearAuthenticationAttributes(request);
	}
	
	protected final void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        session.removeAttribute(WebAttributes.LAST_USERNAME);
    }
	
	@Autowired
	public void setHomeServiceCache(HomeServiceCache homeServiceCache) {
		this.homeServiceCache = homeServiceCache;
	}
}
